package com.ym.controller;

import com.baidu.aip.util.Base64Util;
import com.ym.utils.FileUtil;
import com.ym.utils.GetTon;
import com.ym.utils.GsonUtils;
import com.ym.utils.HttpUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Base64.Decoder;

/**
 *
 * @author: likang
 * @date: 2020/1/8 14:02
 * @description: 登录控制器
 */
@Controller
public class LoginController {

    private static String accessToken;

    @Value("${myj.baidu.search.URL}")
    private String SEARCHURL;
    @Value("${myj.baidu.match.URL}")
    private String MATCHURL;

    /*
     * @Description: 登录按钮
     * @author: likang
     * @date: 2020/1/8 14:02
     * @params: [request, response, model]
     * @return: java.lang.String
     * @exception:
     */
    @RequestMapping("/facelogin.action")
    public @ResponseBody String onListStudent(HttpServletRequest request, HttpServletResponse response, Model model) {
        String img = request.getParameter("img"); // 图像数据
        try {
            boolean tag = search(img);
            PrintWriter writer = response.getWriter();
            if (tag) {
                request.getSession().setAttribute("user", "likang");
                writer.print(tag);
                writer.close();
                return null;
            }else {
                writer.print(tag);
                writer.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/404.jsp";
        }
        return null;
    }

    public boolean search(String img) {

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", img);
            map.put("liveness_control", "NORMAL");
            map.put("group_id_list", "group_repeat");
            map.put("image_type", "BASE64");
            map.put("quality_control", "LOW");

            String param = GsonUtils.toJson(map);

            accessToken = GetTon.getToken();

            String result = HttpUtil.post(SEARCHURL, accessToken, "application/json", param);
            System.out.println(result);

            net.sf.json.JSONObject fromObject = net.sf.json.JSONObject.fromObject(result);
            net.sf.json.JSONObject resultscore = fromObject.getJSONObject("result");
            net.sf.json.JSONArray jsonArray = resultscore.getJSONArray("user_list");

            for (int i = 0; i < jsonArray.size(); i++) {
                net.sf.json.JSONObject object = (net.sf.json.JSONObject) jsonArray.get(i);
                double resultList = object.getDouble("score");
                System.out.println(resultList);
                if (resultList >= 90) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /*
     * @Description: 人脸对比
     * @author: likang
     * @date: 2020/1/8 14:12
     * @params: [request, imStr1, imgStr2]
     * @return: boolean
     * @exception:
     */
    public boolean getResult(HttpServletRequest request, String imStr1, String imgStr2) {

        accessToken = GetTon.getToken();
        boolean flag = false;

        try {
            byte[] bytes1 = FileUtil.readFileByBytes("");
            byte[] bytes2 = FileUtil.readFileByBytes("");
            String image1 = Base64Util.encode(bytes1);
            String image2 = Base64Util.encode(bytes2);

            List<Map<String, Object>> images = new ArrayList<>();

            Map<String, Object> map1 = new HashMap<>();
            map1.put("image", image1);
            map1.put("image_type", "BASE64");
            map1.put("face_type", "LIVE");
            map1.put("quality_control", "LOW");
            map1.put("liveness_control", "NORMAL");

            Map<String, Object> map2 = new HashMap<>();
            map2.put("image", image2);
            map2.put("image_type", "BASE64");
            map2.put("face_type", "LIVE");
            map2.put("quality_control", "LOW");
            map2.put("liveness_control", "NORMAL");

            images.add(map1);
            images.add(map2);

            String param = GsonUtils.toJson(images);

            String result = HttpUtil.post(MATCHURL, accessToken, "application/json", param);
            System.out.println(result);
            // return result;
            JSONObject fromObject = JSONObject.fromObject(result);

            JSONArray jsonArray = fromObject.getJSONArray("result");

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject object = (JSONObject) jsonArray.get(i);
                double resultList = object.getDouble("score");
                if (resultList >= 90) {
                    flag = true;

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}
